// 全局变量
let currentCategoryId = null;
let keyword = null;
let currentPage = 1;
let pageSize = 12;
let totalPages = 0;
let priceFilter = 'all';
let degreeFilter = 'all';
let sortType = 'default';

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化页面
    initPage();
    
    // 绑定事件
    bindEvents();
});

// 初始化页面
function initPage() {
    // 获取URL参数
    const urlParams = new URLSearchParams(window.location.search);
    currentCategoryId = urlParams.get('categoryId');
    keyword = urlParams.get('keyword');
    
    // 加载分类列表
    loadCategories();
    
    // 加载商品列表
    loadProducts();
    
    // 更新面包屑导航
    updateBreadcrumb();
}

// 加载分类列表
function loadCategories() {
    ApiService.category.getAllCategories()
        .then(response => {
            if (response.data && response.data.length > 0) {
                renderCategories(response.data);
            }
        })
        .catch(error => {
            console.error("获取分类数据失败:", error);
            document.getElementById('category-list').innerHTML = '<li class="category-item">加载分类失败，请刷新重试</li>';
        });
}

// 渲染分类列表
function renderCategories(categories) {
    const categoryList = document.getElementById('category-list');
    categoryList.innerHTML = '';
    
    categories.forEach(category => {
        const li = document.createElement('li');
        li.className = 'category-item layui-menu-item-parent';
        li.setAttribute('lay-options', '{type: "parent"}');
        
        // 创建分类标题
        const titleDiv = document.createElement('div');
        titleDiv.className = 'layui-menu-body-title';
        titleDiv.innerHTML = `
            ${category.categoryName}
            <i class="layui-icon layui-icon-right"></i>
        `;
        
        li.appendChild(titleDiv);
        
        // 如果有子分类，创建子分类面板
        if (category.children && category.children.length > 0) {
            const panelDiv = document.createElement('div');
            panelDiv.className = 'layui-panel layui-menu-body-panel';
            
            const subUl = document.createElement('ul');
            
            category.children.forEach(subCategory => {
                const subLi = document.createElement('li');
                
                // 如果子分类还有子分类，设置为父级
                if (subCategory.children && subCategory.children.length > 0) {
                    subLi.className = 'layui-menu-item-parent';
                    subLi.setAttribute('lay-options', '{type: "parent"}');
                    
                    const subTitleDiv = document.createElement('div');
                    subTitleDiv.className = 'layui-menu-body-title';
                    subTitleDiv.textContent = subCategory.categoryName;
                    
                    subLi.appendChild(subTitleDiv);
                } else {
                    // 没有子分类的情况
                    const subTitleDiv = document.createElement('div');
                    subTitleDiv.className = 'layui-menu-body-title';
                    subTitleDiv.innerHTML = `<a href="catalog.html?categoryId=${subCategory.id}">${subCategory.categoryName}</a>`;
                    
                    subLi.appendChild(subTitleDiv);
                }
                
                subUl.appendChild(subLi);
            });
            
            panelDiv.appendChild(subUl);
            li.appendChild(panelDiv);
        }
        
        categoryList.appendChild(li);
    });
    
    // 初始化layui菜单
    // layui.use('dropdown', function(){
    //     var dropdown = layui.dropdown;
    //     dropdown.render({
    //         elem: '#category-list',
    //         trigger: 'hover'
    //     });
    // });
}

// 加载商品列表
function loadProducts() {
    // 显示加载状态
    document.getElementById('product-grid').innerHTML = `
        <div class="loading-container">
            <div class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></div>
            <p>正在加载商品...</p>
        </div>
    `;
    
    // 构建请求参数
    const params = {
        page: currentPage-1,
        size: pageSize
    };
    
    if (currentCategoryId) {
        params.categoryId = currentCategoryId;
    }

    if (keyword) {
        params.keyword = keyword;
    }
    
    if (priceFilter !== 'all') {
        const [min, max] = priceFilter.split('-');
        params.minPrice = min;
        if (max) {
            params.maxPrice = max;
        }
    }
    
    if (degreeFilter !== 'all') {
        params.degree = degreeFilter;
    }
    
    if (sortType !== 'default') {
        params.sort = sortType;
    }
    
    // 发送请求
    ApiService.book.getAllBooks(params)
        .then(response => {
            if (response.data) {
                renderProducts(response.data.content);
                renderPagination(response.data.totalPages);
                totalPages = response.data.totalPages;
            } else {
                document.getElementById('product-grid').innerHTML = '<div class="no-products">暂无商品</div>';
                document.getElementById('pagination').innerHTML = '';
            }
        })
        .catch(error => {
            console.error("获取商品数据失败:", error);
            document.getElementById('product-grid').innerHTML = '<div class="error-message">加载商品失败，请刷新重试</div>';
        });
}

// 渲染商品列表
function renderProducts(products) {
    const productGrid = document.getElementById('product-grid');
    
    if (!products || products.length === 0) {
        productGrid.innerHTML = '<div class="no-products">暂无商品</div>';
        return;
    }
    
    productGrid.innerHTML = '';
    
    products.forEach(product => {
        const discount = product.originalPrice > product.price 
            ? Math.round((1 - product.price / product.originalPrice) * 100) 
            : 0;
        
        const productCard = document.createElement('div');
        productCard.className = 'product-card';
        productCard.innerHTML = `
            <div class="product-image">
                <img src="${product.imageUrl || './img/default-book.jpg'}" alt="${product.title}">
                ${discount > 0 ? `<div class="discount-tag">${discount}% OFF</div>` : ''}
                <div class="product-hover">
                    <button class="quick-view" onclick="window.location.href='detail.html?id=${product.id}'">查看详情</button>
                </div>
            </div>
            <div class="product-info">
                <h3 class="product-title">${product.title}</h3>
                <div class="product-meta">
                    <span>${product.author}</span>
                    <span>${product.degree || '全新'}</span>
                </div>
                <div class="product-price">
                    <span class="current-price">¥${product.price.toFixed(2)}</span>
                    ${product.originalPrice > product.price ? `<span class="original-price">¥${product.originalPrice.toFixed(2)}</span>` : ''}
                </div>
                <div class="product-actions">
                    <button class="add-to-cart" onclick="addToCart(${product.id})">加入购物车</button>
                    <button class="add-to-wishlist" onclick="addToWishlist(${product.id})">收藏</button>
                </div>
            </div>
        `;
        
        productGrid.appendChild(productCard);
    });
}

// 渲染分页
function renderPagination(totalPages) {
    const pagination = document.getElementById('pagination');
    
    if (totalPages <= 1) {
        pagination.innerHTML = '';
        return;
    }
    
    let paginationHTML = '';
    
    // 上一页按钮
    paginationHTML += `
        <a href="javascript:;" class="page-btn ${currentPage === 1 ? 'disabled' : ''}" 
           ${currentPage === 1 ? '' : 'onclick="changePage(' + (currentPage - 1) + ')"'}>
            <i class="layui-icon layui-icon-left"></i>
        </a>
    `;
    
    // 页码按钮
    const maxPageButtons = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxPageButtons / 2));
    let endPage = Math.min(totalPages, startPage + maxPageButtons - 1);
    
    if (endPage - startPage + 1 < maxPageButtons) {
        startPage = Math.max(1, endPage - maxPageButtons + 1);
    }
    
    if (startPage > 1) {
        paginationHTML += `<a href="javascript:;" class="page-btn" onclick="changePage(1)">1</a>`;
        if (startPage > 2) {
            paginationHTML += `<span class="page-dots">...</span>`;
        }
    }
    
    for (let i = startPage; i <= endPage; i++) {
        paginationHTML += `
            <a href="javascript:;" class="page-btn ${i === currentPage ? 'active' : ''}" 
               onclick="changePage(${i})">${i}</a>
        `;
    }
    
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            paginationHTML += `<span class="page-dots">...</span>`;
        }
        paginationHTML += `<a href="javascript:;" class="page-btn" onclick="changePage(${totalPages})">${totalPages}</a>`;
    }
    
    // 下一页按钮
    paginationHTML += `
        <a href="javascript:;" class="page-btn ${currentPage === totalPages ? 'disabled' : ''}" 
           ${currentPage === totalPages ? '' : 'onclick="changePage(' + (currentPage + 1) + ')"'}>
            <i class="layui-icon layui-icon-right"></i>
        </a>
    `;
    
    pagination.innerHTML = paginationHTML;
}

// 切换页码
function changePage(page) {
    if (page < 1 || page > totalPages || page === currentPage) {
        return;
    }
    
    currentPage = page;
    loadProducts();
    
    // 滚动到页面顶部
    window.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
}

// 更新面包屑导航
function updateBreadcrumb() {
    if (!currentCategoryId) {
        document.getElementById('current-category').textContent = '全部商品';
        return;
    }
    
    ApiService.category.getCategoryById(currentCategoryId)
        .then(response => {
            if (response.data) {
                document.getElementById('current-category').textContent = response.data.categoryName;
            }
        })
        .catch(error => {
            console.error("获取分类详情失败:", error);
        });
}

// 绑定事件
function bindEvents() {
    // 筛选条件点击事件
    document.querySelectorAll('.filter-option').forEach(option => {
        option.addEventListener('click', function() {
            const filterType = this.dataset.price ? 'price' : (this.dataset.degree ? 'degree' : 'sort');
            
            // 移除同类选项的active类
            document.querySelectorAll(`.filter-option[data-${filterType}]`).forEach(el => {
                el.classList.remove('active');
            });
            
            // 添加active类
            this.classList.add('active');
            
            // 更新筛选条件
            if (filterType === 'price') {
                priceFilter = this.dataset.price;
            } else if (filterType === 'degree') {
                degreeFilter = this.dataset.degree;
            } else if (filterType === 'sort') {
                sortType = this.dataset.sort;
            }
            
            // 重置页码并重新加载商品
            currentPage = 1;
            loadProducts();
        });
    });
}

// 加入购物车
function addToCart(bookId) {
    // 检查是否登录
    const token = localStorage.getItem('token');
    if (!token) {
        // 显示登录弹窗
        document.getElementById('mask').style.display = 'flex';
        return;
    }
    
    ApiService.cart.addToCart(bookId, 1)
        .then(response => {
            if (response.data) {
                // 显示成功提示
                layui.layer.msg('加入购物车成功', {icon: 1});
                
                // 更新购物车数量
                AuthService.updateCartCount();
            }
        })
        .catch(error => {
            console.error("加入购物车失败:", error);
            layui.layer.msg('加入购物车失败，请重试', {icon: 2});
        });
}

// 添加到收藏
function addToWishlist(bookId) {
    // 检查是否登录
    const token = localStorage.getItem('token');
    if (!token) {
        // 显示登录弹窗
        document.getElementById('mask').style.display = 'flex';
        return;
    }
    
    // 这里假设有收藏API，如果没有可以先用提示代替
    layui.layer.msg('收藏功能即将上线', {icon: 6});
    
    // 如果有收藏API，可以使用以下代码
    /*
    ApiService.wishlist.addToWishlist(bookId)
        .then(response => {
            if (response.data) {
                layui.layer.msg('收藏成功', {icon: 1});
            }
        })
        .catch(error => {
            console.error("收藏失败:", error);
            layui.layer.msg('收藏失败，请重试', {icon: 2});
        });
    */
}
